package cn.ch.train.gateway.config;

import cn.ch.train.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(LoginMemberFilter.class);


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        // 排除不需要拦截的请求
        if (path.contains("/admin")
                || path.contains("/hello")
                || path.contains("/train-member/member/login")
                || path.contains("/train-member/member/send-code")) {
            logger.info("该url不需要登录验证：{}", path);
            // 请求继续
            return chain.filter(exchange);
        } else {
            logger.info("该url需要登录验证：{}", path);
        }

        // 获取header的token参数
        String token = exchange.getRequest().getHeaders().getFirst("token");
        logger.info("会员登录验证开始，token为：{}", token);
        if (token == null || token.isEmpty()) {
            logger.info("token为空，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            // 请求中断
            return exchange.getResponse().setComplete();
        }

        // 校验token是否有效，包括token能否解密（是否被改过）、是否过期
        boolean validateFlag = JwtUtil.validate(token);
        if (validateFlag) {
            logger.info("token有效，该请求可放行");
            return chain.filter(exchange);
        } else {
            logger.warn("token无效，请求被拦截");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    /**
     * description：用于确定过滤器的执行顺序，执行顺序按数字升序顺序执行，即0 -> 1 -> 2 ...
     * @return 0
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
